package com.wangbo.restTemplate.aiSchool;

import cn.hutool.core.io.FileUtil;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.File;

public class TestFileSend {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplateBuilder().errorHandler(new DefaultResponseErrorHandler(){
            /**
             * 设置RestTemplate自带的异常处理器不做异常处理
             **/
            @Override
            public void handleError(ClientHttpResponse response) {
            }
        }).build();

        // 文件上传
        File file = new File("D:\\temp\\c.jpg");
        test02(restTemplate, file);
    }

    /**
     * ByteArrayResource 文件上传
     */
    public static void test01(RestTemplate restTemplate) {
        byte[] bytes = FileUtil.readBytes("D:\\temp\\case\\9212.jpg");
        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return "9212.jpg";
            }
        };

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("multipartFile ",byteArrayResource);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject("http://120.92.141.239:8080/aiSchool/sys/media", httpEntity, String.class);
        System.out.println(result);
    }

    /**
     * FileSystemResource 文件上传
     */
    public static void test02(RestTemplate restTemplate, File file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("multipartFile ", new FileSystemResource(file));
        param.add("checkQuality", true);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject("http://139.196.32.4:8080/aiSchool/sys/media", httpEntity, String.class);
        System.out.println(result);
    }
}
